package com.wocai.jrt.orgadmin.issuers.action;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.Cookie;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.wocai.jrt.admin.common.constant.ComConst;
import com.wocai.jrt.orgadmin.issuers.bean.IssuersOrdersResBean;
import com.wocai.jrt.orgadmin.issuers.model.Issuers;
import com.wocai.jrt.orgadmin.issuers.model.IssuersBack;
import com.wocai.jrt.orgadmin.issuers.service.spi.IssuersBackService;
import com.wocai.jrt.orgadmin.issuers.service.spi.IssuersService;
import com.wocai.jrt.orgadmin.orders.bean.OrderReqBean;
import com.wocai.jrt.orgadmin.orders.model.Orders;
import com.wocai.jrt.orgadmin.orders.service.spi.OrdersService;
import com.wocai.jrt.orgadmin.product.model.Product;
import com.wocai.jrt.orgadmin.product.model.ProductGroup;
import com.wocai.jrt.orgadmin.product.service.spi.ProductGroupService;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;
import com.wocai.jrt.orgadmin.setting.model.Setting;
import com.wocai.jrt.orgadmin.setting.service.spi.SettingService;
import com.wocai.jrt.orgadmin.utils.ApiCallUtils;
import com.wocai.jrt.orgadmin.utils.ImgType;
import com.wocai.jrt.orgadmin.utils.MyFileUtils;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 发行方控制器
 * 
 * @author yinlei
 * @date 2016-3-7 15:37:31
 */
@Controller
@RequestMapping("/publisher")
public class PublisherAction extends GenericAction<Issuers> {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(PublisherAction.class);
	@Inject
	private OrdersService ordersServiceImpl;
	@Inject
	private ProductService productServiceImpl;
	@Inject
	private BCryptPasswordEncoder bcryptPasswordEncoder;
	@Inject
	private ProductGroupService productGroupServiceImpl;
	@Inject
	private IssuersService issuersServiceImpl;
	@Inject
	private SettingService settingServiceImpl;
	@Inject
	private IssuersBackService issuersBackServiceImpl;

	@RequestMapping("/login")
	public String login(String authError) {
		return "publishLogin";
	}

	@RequestMapping("/platform")
	public String platofrm() {
		Issuers issuers = UserUtils.getPublisher();
		if (issuers != null) {
			setAttributeToSession(ComConst.CONTEXT_PUBLISHER, issuers);

			// 登录成功，将账号和机构代码，放入cookie中
			// 集群状态下同步用户信息是需要的，将状态放在客户端
			String account = "";
			try {
				account = URLEncoder.encode(issuers.getAccount(), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// ignore
			}
			Cookie cookie = new Cookie(ComConst.SEC_ACCOUNT, account);
			cookie.setMaxAge(Integer.MAX_VALUE);
			cookie.setPath("/");
			getHttpServletResponse().addCookie(cookie);

			cookie = new Cookie(ComConst.SEC_TENANT, issuers.getOrgCode());
			cookie.setMaxAge(Integer.MAX_VALUE);
			cookie.setPath("/");
			getHttpServletResponse().addCookie(cookie);
			return "publisher/platform";
		} else { // 没有获取到用户信息，调到登录页
			return "redirect:/publisher/login";
		}
	}

	@RequestMapping("/sessionTimeout")
	public String sessionTimeout() {
		// 记住用户名
		Cookie[] cookies = getHttpServletRequest().getCookies();
		for (Cookie cookie : cookies) {
			String name = cookie.getName();
			if (name.equals(ComConst.SEC_ACCOUNT)) {
				String account = "";
				try {
					account = URLDecoder.decode(cookie.getValue(), "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// ignore
				}
				setAttributeToRequest(ComConst.SEC_ACCOUNT, account);
			} else if (name.equals(ComConst.SEC_TENANT)) {
				setAttributeToRequest(ComConst.SEC_TENANT, cookie.getValue());
			}
		}
		return "login"; // session超时，到登录页面
	}

	@RequestMapping("/product/list")
	public String productList(Product p, Map<String, Object> maps) {
		try {
			ProductGroup productGroupParam = new ProductGroup();
			productGroupParam.setOrgId(UserUtils.getPublisher().getOrgId());
			List<ProductGroup> productGroupList = productGroupServiceImpl
					.pagedList(productGroupParam);
			maps.put("productGroupList", productGroupList);
		} catch (Exception e) {
			LOGGER.error("get record list error, errorMsg=[{}].",
					e.getMessage());
		}

		return "publisher/product/list";
	}

	@ResponseBody
	@RequestMapping("/product/query")
	public Map<String, Object> productQuery(@RequestBody Product model) {
		Map<String, Object> map = new HashMap<String, Object>();

		try {
			LOGGER.info("request product query, param = [{}]",
					JSON.toJSONString(model));

			String issId = UserUtils.getIssuersId();
			model.setIssuerId(issId);
			model.setOrgId(UserUtils.getIssuersOrgId());

			if (null != model.getCreateEndTime()) {
				model.setCreateEndTime(new DateTime(model.getCreateEndTime())
						.plusSeconds(59).plusMinutes(59).plusHours(23).toDate());
			}

			int size = productServiceImpl.issuersCountBy(model);
			if (model.getPageSize() == -1) {
				model.setStart(null);
			}

			List<Product> list = new ArrayList<Product>();

			if (size > 0) {
				list = issuersServiceImpl.issuersPagedList(model);
				LOGGER.info("query product list success, size = [{}]",
						list.size());

			}

			map.put("aaData", list); // 返回的数据
			map.put("iTotalRecords", size); // 总记录数
			map.put("iTotalDisplayRecords", size); // 显示的记录数

		} catch (Exception e) {
			LOGGER.error("request product query error, msg = [{}]",
					e.getMessage());
		}

		return map;
	}

	/**
	 * 跳转订单List页面。
	 * 
	 * @param model
	 *            参数
	 * @return 订单List页面
	 */
	@RequestMapping("/orders/list/{id}")
	public String list(@PathVariable("id") String id, Map<String, Object> maps) {
		maps.put("productId", id);

		Setting setting = new Setting();
		setting.setOrgId(UserUtils.getIssuersOrgId());
		setting.setKeyName("orderRevisit");

		maps.put("needRevisit", settingServiceImpl.unique(setting)
				.getKeyValue());
		return "publisher/orders/list";
	}

	/**
	 * 获得订单List，Json格式。
	 * 
	 * @param model
	 *            参数
	 * @return 订单List
	 */
	@ResponseBody
	@RequestMapping(value = "/orders/query", method = RequestMethod.POST)
	public Map<String, Object> query(@RequestBody OrderReqBean model) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			model.setOrgId(UserUtils.getIssuersOrgId());
			model.setOrderBy("FIELD(o.state, 5) ASC,order_time desc");
			LOGGER.info("获取订单的model参数: [{}]", JSON.toJSONString(model));
			List<IssuersOrdersResBean> list = ordersServiceImpl
					.getIssuersOrdersResBeanList(model);
			// 统计的时候，不需要分页
			model.setPage(null);
			long totalRecord = ordersServiceImpl.getIssuersOrdersCount(model);

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("order query success.");
			}
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("order query error, msg=[{}]", e.getMessage());
		}
		return result;
	}

	/**
	 * 发起回访
	 * 
	 * @param model
	 *            参数
	 * @return Jsonbean
	 */
	@ResponseBody
	@RequestMapping("/startCallback/{id}")
	public JsonBean startCallback(@PathVariable("id") String id) {
		JsonBean bean = new JsonBean();
		if (StringUtils.isBlank(id)) {
			bean.setCode(0);
			bean.setMessage("参数异常");
			return bean;
		}
		try {
			Orders o = new Orders();
			o.setId(id);
			o.setRevisitState(2);
			LOGGER.info("startCallback update record params is:[{}].", o);
			int result = ordersServiceImpl.sendRevisit(o);
			if (result == 1) {
				bean.setCode(1);
				bean.setMessage("发起回访成功！");
			} else {
				bean.setCode(0);
				bean.setMessage("发起回访出错！");
			}
		} catch (Exception e) {
			LOGGER.info("startCallback update record error due to:[{}].",
					e.getMessage());
			bean.setCode(0);
			bean.setMessage("发起回访出错！");
		}
		return bean;
	}

	/**
	 * 查看回访
	 * 
	 * @param model
	 *            参数
	 * @return Jsonbean
	 */
	@ResponseBody
	@RequestMapping("/reviewCallback/{id}")
	public JsonBean reviewCallback(@PathVariable("id") String id) {
		JsonBean bean = new JsonBean();
		if (StringUtils.isBlank(id)) {
			bean.setCode(0);
			bean.setMessage("参数异常");
			return bean;
		}
		try {
			Orders o = ordersServiceImpl.get(id);
			LOGGER.info("Orders record params is:[{}].", o);
			if (null == o) {
				bean.setCode(0);
				bean.setMessage("id不能为空");
				LOGGER.info("id不能为空.");
				return bean;
			}
			IssuersBack ib = new IssuersBack();
			ib.setOrderId(o.getOrderId());
			ib = issuersBackServiceImpl.unique(ib);
			if (null == ib) {
				bean.setCode(0);
				bean.setMessage("不存在此回访");
				LOGGER.info("不存在此回访.");
				return bean;
			} else {
				bean.setCode(1);
				bean.setMessage(SUCCESS);
				bean.setData(ib);
			}
		} catch (Exception e) {
			LOGGER.info("startCallback update record error due to:[{}].",
					e.getMessage());
			bean.setCode(0);
			bean.setMessage("发起回访出错！");
		}
		return bean;
	}

	/**
	 * 上传电子公章
	 * 
	 * @param model
	 *            参数
	 * @return Jsonbean
	 */
	@ResponseBody
	@RequestMapping("/uploadElectronicSeal")
	public JsonBean uploadElectronicSeal(@RequestParam("id") String id,
			@RequestParam("electronicSeal") MultipartFile electronicSeal) {
		JsonBean jsonBean = new JsonBean();
		getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		try {
			// 先上传电子公章
			String Electronic = MyFileUtils
					.uploadImg(electronicSeal, ImgType.values()[2]);
			Orders orderData = new Orders();

			// 这里不是orderId而是id
			orderData.setId(id);
			orderData.setElectronic(Electronic);
			orderData.setStampAdded(true);
			orderData.setRevisitState(3);
			int result = ordersServiceImpl.updateById(orderData);
			if(result == 1){
				jsonBean.setCode(1);
				jsonBean.setMessage("加盖电子公章成功");
			}else{
				jsonBean.setCode(0);
				jsonBean.setMessage("加盖电子公章失败");
			}
			Orders o = ordersServiceImpl.get(id);
			// 生成电子合同
			ApiCallUtils.callToCreateContact(o.getOrderId());
		} catch (Exception e) {
			jsonBean.setCode(0);
			jsonBean.setMessage("upload ElectronicSealImage falure");
			LOGGER.error("upload ElectronicSealImage falure, msg = [{}]",
					e.getMessage());
		}
		return jsonBean;
	}

	/**
	 * 更新员工单个的一些信息，密码和解除设备绑定
	 * 
	 * @param model
	 *            要更新的员工信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/updateEmpPassword")
	public JsonBean updateEmpPassword(@RequestBody Issuers model) {
		JsonBean bean = new JsonBean();

		String issuersId = UserUtils.getIssuersId();

		if (StringUtils.isBlank(issuersId)) {
			bean.setMessage("Update Employee, Params is required.");
			return bean;
		}
		String loginPwd = model.getPassword();
		if (StringUtils.isAnyBlank(loginPwd)) {
			bean.setMessage("新密码不能为空！");
			return bean;
		}

		if (loginPwd.length() < 6 || loginPwd.length() > 20) {
			bean.setMessage("密码设置不正确。");
			return bean;
		}
		try {
			Issuers issuers = issuersServiceImpl.get(issuersId);
			if (null == issuers) {
				bean.setMessage("id不能为空！");
				return bean;
			}
			if (!bcryptPasswordEncoder.matches(model.getUserOldpasswd(),
					issuers.getPassword())) {
				bean.setMessage("原密码错误！");
				return bean;
			}

			loginPwd = bcryptPasswordEncoder.encode(loginPwd);
			issuers.setPassword(loginPwd);
			int result = issuersServiceImpl.updateById(issuers);
			if (result == 1) {
				bean.setMessage("密码修改成功！");
				bean.setCode(1);
				LOGGER.info("update record success.");
			} else {
				bean.setMessage("修改密码出错！");
				LOGGER.error("update record error.");
			}

		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			bean.setMessage("修改密码出现异常！");
		}
		return bean;
	}
}
